import React, { useState, useEffect } from 'react';
import { GetRouteCache, CacheRouteParams } from '@/utils/route-utils';

interface PullDataParm {
  params: Record<string, any>,
  setData: React.Dispatch<React.SetStateAction<any | []>>,
  setLastId: React.Dispatch<React.SetStateAction<string>>,
  setSurplusTotal: React.Dispatch<React.SetStateAction<number | 0>>,
}

// 配合antd-refresh-list,生产所需函数方法及state
export function useRefreshList<
  ListParams extends Record<string, unknown> = any,
  SearchData extends Record<string, unknown> = any,
  Datasource = any
>({
  routeProps,
  cacheRouteList = [],
  initParams = { pageSize: 10 } as any,
  initSearchData = {},
  pullData = async () => { }
}: {
  routeProps?: RouterProps;
  cacheRouteList?: string[]; // 进入对应的路由时缓存当前数据
  initParams?: ListParams;
  initSearchData?: SearchData | {};
  // 调用接口的方法，接受setDatasource作为参数, 在获取数据后，通过其将数据注回useRefreshList
  pullData: (pullDataParm: PullDataParm) => Promise<any>;
}) {
  const [routeCache, setRouteCache] = useState(GetRouteCache(routeProps.location?.pathname)); // 缓存的数据，返回页面取
  const [showDom, setShowDom] = useState<boolean>(false);
  const [pageNum, setPageIndex] = useState<number>(1);
  const [dataSource, setDatasource] = useState<Datasource[] | []>([]);
  const [reqParams, setReqParams] = useState<ListParams>({} as ListParams);
  const [searchData, setSearchData] = useState<SearchData | Record<string, unknown>>(initSearchData);
  const [surplusTotal, setSurplusTotal] = useState(0);
  const [lastId, setLastId] = useState<string>();
  const [refreshing, setRefreshing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);

  // 挂载的时候处理请求参数
  useEffect(() => {
    // 如果有缓存，则参数从缓存取,否则为默认
    setReqParams(routeCache?.reqParams || { ...initParams, });
    setSearchData(routeCache?.searchData || { ...initSearchData })
    setPageIndex(routeCache?.pageNum || 1)
  }, []);

  // 监听参数变动
  useEffect(() => {
    if (!Object.keys(reqParams).length) return;
    changeReqParams();
  }, [reqParams, searchData]);

  // 请求参数发生变化重新请求
  const changeReqParams = async () => {
    setShowDom(false);
    await pullData({
      setLastId,
      setSurplusTotal,
      params: { pageNum, ...reqParams, ...searchData },
      setData: setDatasource,
    });
    setShowDom(true);
    scrollFromCache();
    setPageIndex(routeCache?.pageNum || 1)
    // setPageIndex(1)
  }

  // 滚动到从缓存取到的位置
  const scrollFromCache = () => {
    try {
      if (routeCache?.scrollTop) {
        const scrollDom = document.querySelector('.am-list-view-scrollview');
        setTimeout(() => { scrollDom && (scrollDom.scrollTop = routeCache?.scrollTop) });
      }
    } finally {
      setRouteCache({});  // 滚动完之后清除缓存state
    }
  };

  // 路由离开时判断是否将当前数据缓存
  const routeWillLeave = (nextRoute) => {
    try {
      const scrollDom = document.querySelector('.am-list-view-scrollview');
      const currentScrollTop = scrollDom?.scrollTop;
      CacheRouteParams({
        currentLocation: routeProps.location,
        nextRoute,
        targetRouteList: cacheRouteList || [],// 路由离开时判断是否需要缓存路由数据，缓存的路由
        cacheData: {
          pageNum, // 页码
          reqParams,// 请求条件
          searchData,
          scrollTop: currentScrollTop // 滚动高度
        }
      });
    } catch (error) {
      console.error(error)
    }
    return true // 不阻断路由跳转
  }

  // 搜索 | 切换搜索条件
  const handleSearch = (values = {}) => {
    setPageIndex(routeCache?.pageNum || 1)
    setSearchData(values)
  }

  // 重置，将搜索依赖及表格接口依赖重置为init
  const handleReset = () => {
    setReqParams({
      ...initParams
    });
    setSearchData(initSearchData);
  };

  // 刷新列表
  const handleRefresh = async () => {
    setRefreshing(true)
    await pullData({
      setLastId,
      setSurplusTotal,
      params: { ...reqParams, ...searchData },
      setData: setDatasource,
    });
    setShowDom(true)
    setRefreshing(false)
    setPageIndex(1)
  };

  // 加载更多
  const handleLoadMore = async () => {
    if (!surplusTotal || loadingMore) return;
    setLoadingMore(true)
    await pullData({
      params: { lastId, ...reqParams, ...searchData },
      setLastId,
      setSurplusTotal,
      setData: setDatasource,
    });
    setShowDom(true)
    setLoadingMore(false)
    setPageIndex(pageNum + 1)
  }

  return {
    // 缓存路由数据
    routeCache,
    setRouteCache,
    // 加载中
    refreshing,
    setRefreshing,
    // 加载更多
    loadingMore,
    setLoadingMore,
    // 首次 | 重新加载数据（切换搜索条件）完成
    showDom,
    setShowDom,
    // 数据剩余总数
    surplusTotal,
    setSurplusTotal,
    // 表格数据源
    dataSource,
    setDatasource,
    // 接口请求参数
    reqParams,
    setReqParams,
    // 搜索依赖state
    searchData,
    setSearchData,
    // 搜索操作
    handleSearch,
    // 重置操作
    handleReset,
    //刷新数据
    handleRefresh,
    // 加载更多
    handleLoadMore,
    // 设置路由缓存
    routeWillLeave,
  };
}
